package com.dyb.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.UnsupportedEncodingException;
import java.util.Scanner;

/**
 * 回显客户端
 * @author dyb
 * @date 2020/7/24
 */
public class NettyEchoClient {

    private String ip;
    private int port;


    Bootstrap b = new Bootstrap();

    public NettyEchoClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyEchoClient("127.0.0.1", 8888).runClient();

    }

    public void runClient() throws InterruptedException {
        // 反应器线程组
        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            // 1.设置反应器线程组
            b.group(workerLoopGroup);
            // 2.设置nio类型通道
            b.channel(NioSocketChannel.class);
            // 3.设置监听端口
            b.remoteAddress(ip, port);
            // 4.设置通道参数
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            // 5.装配子通道流水线
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(EchoClientHandler.INSTANCE);
                }
            });

            ChannelFuture future = b.connect();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()) {
                        System.out.println("客户端连接成功");
                    } else {
                        System.out.println("客户端连接失败");
                    }
                }
            });

            future.sync();

            Channel channel = future.channel();
            Scanner sc = new Scanner(System.in);
            while (sc.hasNext()) {
                String next = sc.next();
                ByteBuf buffer = channel.alloc().buffer();
                buffer.writeBytes(next.getBytes("UTF-8"));
                channel.writeAndFlush(buffer);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            // 释放所有资源
            workerLoopGroup.shutdownGracefully();
        }
    }

}

/**
 * 客户端回显处理
 * @author dyb
 * @date 2020/7/24
 */
@ChannelHandler.Sharable
class EchoClientHandler extends ChannelInboundHandlerAdapter {
    // 没有共享资源可以使用在Channel中共享
    public static final EchoClientHandler INSTANCE = new EchoClientHandler();

    private EchoClientHandler() {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
        // 这里创建的buf记得释放
        ByteBuf byteBuf = (ByteBuf) msg;
        int length = byteBuf.readableBytes();
        byte[] arr = new byte[length];

        byteBuf.getBytes(0, arr);

        System.out.println("接收到内容："+ new String(arr, "utf-8"));

        // 向后传递自动释放byteBuf
        ctx.fireChannelRead(msg);
    }
}